package com.bluexmicro.module_componment.scan

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bluexmicro.module_componment.OnItemClickCallback
import com.bluexmicro.module_componment.R
import com.bluexmicro.module_componment.databinding.ItemInnerDeviceBinding
import com.bluexmicro.module_componment.file.root
import org.w3c.dom.Text

class ScanAdapter(
    callback: ScanDiffCallback = ScanDiffCallback(),
    private val onItemClick: OnItemClickCallback
) : ListAdapter<BleDevice, ScanViewHolder>(callback) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ScanViewHolder {
        val binding = ItemInnerDeviceBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ScanViewHolder(binding)
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ScanViewHolder, position: Int) {
        holder.binding.apply {
            val bleDevice = currentList[position]
            deviceNameTx.text = bleDevice.name
            macTx.text = bleDevice.mac
            localNameTx.visibility = if (!bleDevice.localName.isNullOrEmpty()) {
                localNameTx.text = bleDevice.localName
                View.VISIBLE
            } else {
                View.GONE
            }
            rssiTx.text = "${bleDevice.rssi}mdb"
            connectableTx.visibility = if (bleDevice.connectable) View.VISIBLE else View.GONE
            val res = if (bleDevice.rssi > -60) {
                R.drawable.ic_strong_signal
            } else if (bleDevice.rssi > -90) {
                R.drawable.ic_medium_signal
            } else {
                R.drawable.ic_weak_signal
            }
            rssiView.setImageDrawable(ContextCompat.getDrawable(rssiView.context, res))

            root.setOnClickListener {
                onItemClick.invoke(holder.adapterPosition)
            }
        }
    }

}

class ScanViewHolder(val binding: ItemInnerDeviceBinding) : RecyclerView.ViewHolder(binding.root)

class ScanDiffCallback : DiffUtil.ItemCallback<BleDevice>() {

    override fun areItemsTheSame(oldItem: BleDevice, newItem: BleDevice): Boolean {
        return oldItem.mac == newItem.mac
    }

    override fun areContentsTheSame(oldItem: BleDevice, newItem: BleDevice): Boolean {
        return oldItem.timeMills == newItem.timeMills
    }

}